import { Model } from './model'
import { getTargetByName, setTargetByName } from './core'
import dataProvider from './dataProvider'
import { createGraphqlClient } from './graphql'
import { Type } from './common';
import { useState } from 'react';
export function useDataProvider() {
    const client = createGraphqlClient();
    return dataProvider(client)
}
export function useModel<T>(name: string | Type<T>) {
    let target = name;
    if (typeof name === 'string') {
        target = getTargetByName(name)
    }
    if (!target) throw new Error(`没有找到相应model`)
    const dataProvider = useDataProvider()
    return new Model<T>(dataProvider, target as Type<T>)
}

export function useModelTable<T>(table: string, primaryType: string, primary: string) {
    const dataProvider = useDataProvider()
    const type = { resource: table, primaryType, primary } as Type<T>
    setTargetByName(table, type)
    return new Model<T>(dataProvider, type)
}

export function useCount() {
    const [count, setCount] = useState<number>(0)
    return {
        count,
        setCount: () => setCount(count + 1)
    }
}


export function useActiveKey(key: string) {
    const [activeKey, setActiveKey] = useState<string>(key)
    return {
        activeKey,
        setActiveKey
    }
}